package org.taobao.ibatiside.ui.action;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.datatools.connectivity.IConnectionProfile;
import org.eclipse.datatools.connectivity.sqm.core.rte.ICatalogObject;
import org.eclipse.datatools.modelbase.sql.tables.Column;
import org.eclipse.datatools.modelbase.sql.tables.Table;
import org.eclipse.datatools.sqltools.sql.util.ModelUtil;
import org.eclipse.emf.common.util.EList;
import org.taobao.ibatiside.ui.Activator;

public class DseNewInsertAction extends DseViewerAction {
	public static final String ID="org.taobao.ibatiside.ui.action.dse.insert";

	public DseNewInsertAction() {
		super();
		setId(ID);
		setText("New Insert");
		setImageDescriptor(Activator.getIcon("op16/insert.png"));
		setDescription("Create a new Insert node in existed iBATIS configuration file");
	}
	@Override
	protected String sampleSQL() {
		Table table = getSelectedElement();
		IConnectionProfile icp = ModelUtil.getConnectionProfile(((ICatalogObject)table).getCatalogDatabase());
		StringBuffer sb = new StringBuffer("insert into ");
		sb.append(nameHelper.getQualifiedNameInSQLFormat(table));
		EList columns = table.getColumns();
		List<Column> insert_columns = new ArrayList<Column>(columns.size());
		sb.append('(');
		for (int i = 0; i < columns.size(); i++){
			Column column = (Column) columns.get(i);
			String name = nameHelper.getNameInSQLFormat(column);
			if (column.getDefaultValue() == null){
				insert_columns.add(column);
				if (i > 0) sb.append(',');
				sb.append(name);
			}
		}
		sb.append(") values(");
		for (int i = 0; i < insert_columns.size(); i++){
			Column column = (Column) columns.get(i);
			if (i > 0) sb.append(',');
			if (column.isNullable()){
				sb.append("null");
			}else{
				sb.append(dtpFacade.getSampleValue(icp, column.getDataType()));
			}
		}
		sb.append(")");
		return sb.toString();
	}
}
